package com.chenshu.transaction.controller;

import com.chenshu.transaction.model.UserInfo;
import com.chenshu.transaction.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created with IntelliJ IDEA
 * Description
 * User：chenshu
 * Date：2024-04-26
 * Time：14:44
 */
@RequestMapping("/user")
@RestController
@Slf4j
public class UserController {
    @Autowired
    private DataSourceTransactionManager dataSourceTransactionManager;

    @Autowired
    private TransactionDefinition transactionDefinition;

    @Autowired
    UserService userService;

//    @RequestMapping("/registry")
//    public String registry(UserInfo userInfo) {
//        //获取事务
//        TransactionStatus transaction = dataSourceTransactionManager.getTransaction(transactionDefinition);
//
//        Integer result = userService.insertUser(userInfo);
//        log.info("插入了" + result + "条数据～");
//        //回滚/提交事务
//        dataSourceTransactionManager.rollback(transaction);
//
//        return "注册成功";
//    }

    @RequestMapping("/registry")
    @Transactional(rollbackFor = {Exception.class}, isolation = Isolation.DEFAULT)
    public String registry(UserInfo userInfo) {
        Integer result = userService.insertUser(userInfo);
        log.info("插入了" + result + "条数据～");
        try {
            int a = 10/0;
        } catch (Exception e) {
            log.warn("发生了异常..");
            //throw e;
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return "注册成功";
    }
}
